package vtt.android.lichphatsongbd.fragments;

import java.io.File;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import vtt.android.library.utils.VttGA;
import vtt.android.library.utils.VttLog;
import vtt.android.library.utils.VttUtils;
import vtt.android.lichphatsongbd.R;
import vtt.android.lichphatsongbd.dialogs.DialogManager;
import vtt.android.lichphatsongbd.dialogs.DialogManager.IDialogListener;
import vtt.android.lichphatsongbd.fragments.LichPhatSongFragment.AndroidBridge;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdView;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * A placeholder fragment containing a simple view.
 */
public class SopcastLinkFragment extends BaseWebFragment {
	
	private View mLPSRootView;
	private String fontSize;
	
	private DownloadManager manager;
	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static SopcastLinkFragment newInstance(int sectionNumber) {
		SopcastLinkFragment fragment = new SopcastLinkFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		manager = (DownloadManager)  mParentAct.getSystemService(Context.DOWNLOAD_SERVICE);
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		fontSize = (mParentAct.getResources().getDisplayMetrics().density  * 120) + "%";
		log.d("VTT>>> fontSize " + fontSize);
		
		mLPSRootView = inflater.inflate(R.layout.fragment_cm_webview, container, false);
		mProgressBar = (SmoothProgressBar) mLPSRootView.findViewById(R.id.progressbar_loading);

		// Look up the AdView as a resource and load a request.
		AdView adView = (AdView) mLPSRootView.findViewById(R.id.adView);
		// load admob
		loadAdmob(adView);
				
		// init webview
		mWebView = (WebView) mLPSRootView.findViewById(R.id.webView1);
		// init common webview
		initCommonWebview();
		
		// prevent javascript of this page
		mWebView.getSettings().setJavaScriptEnabled(false);
		mWebView.setWebViewClient(new WebClient());
		mWebView.setLongClickable(false);
		//mWebView.addJavascriptInterface(new AndroidBridge(), "Android");
		mWebView.setInitialScale(115);
		
		if (Build.VERSION.SDK_INT >= 11){
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
		
		// If there is a previous instance restore it in the webview
	    mWebView.loadUrl(getString(R.string.url_sopcast_1));	
	    // TODO request HTML
	    //new SopcastLinkTask().execute(getString(R.string.url_sopcast_1));

		return mLPSRootView;
	}
	
//	@Override
//	protected void reloadPage() {
//	    new SopcastLinkTask().execute(getString(R.string.url_sopcast_1));
//	}
	
	class WebClient extends WebViewClient {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			mProgressBar.progressiveStart();
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			log.d("VTT>>> shouldOverrideUrlLoading " + url);
			
			if(url.startsWith("sop://")){
				
				PackageManager pm = mParentAct.getPackageManager();
				Intent appStartIntent = pm.getLaunchIntentForPackage("org.sopcast.android");
				if (null != appStartIntent) {
					Uri uri = Uri.parse(url);
					appStartIntent.setData(uri);
					try {
						mParentAct.startActivity(appStartIntent);
						VttGA.sendEvent(mParentAct, "start sopcast", "start sopcast", "", 0);
					} catch (ActivityNotFoundException e) {
						Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);
						try {
							startActivity(myAppLinkToMarket);
						} catch (ActivityNotFoundException ex) {
							VttGA.sendException(mParentAct, "Không mở được sopcast");
						}
					}
					
				} else {
					mDialogManager.showCommonDialog(DialogManager.DIALOG_TYPE_WARNING, 
							getString(R.string.msg_title_notice),
							getString(R.string.msg_sopcast_warning_install), new IDialogListener() {
								
								@Override
								public void onOkClick() {
									VttGA.sendEvent(mParentAct, "onOkClick", "close sopcast dialog", "", 0);
									/*try {
									    downloadApp(mParentAct, getString(R.string.url_sopcast_apk_link));
                                    } catch (Exception e) {
                                        if(getActivity() == null){
                                            return;
                                        }
                                        Toast.makeText(mParentAct, "Có lỗi xảy ra, tải sopcast thất bại, vui long thử lại!", 1).show();
                                        VttGA.sendException(mParentAct, "downloadApp sopcast error " + e.getMessage());
                                    }*/
								}
								
								@Override
								public void onCancelClick() {
									VttGA.sendEvent(mParentAct, "onCancelClick", "close dialog", "", 0);
								}
							});
				}
				
				return true;
			}
			
			return super.shouldOverrideUrlLoading(view, url);
		}
	}
	
	@Override
	public void onResume() {
		mParentAct.registerReceiver(receiverDownloadListener, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
		super.onResume();
	}
	
	@Override
	public void onStop() {
		try {
			mParentAct.unregisterReceiver(receiverDownloadListener);
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onStop();
	}
	
	// register download finish receiver
	private BroadcastReceiver receiverDownloadListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            	
                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                log.d("VTT>>> downloadId " + downloadId);
                
                Query query = new Query();
                query.setFilterById(downloadId);
                Cursor c = manager.query(query);
                if (c.moveToFirst()) {
					int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
					if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
						String apkUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
						log.d("VTT>>> uriString " + apkUri);
						// install APK
						Intent installApk = new Intent(Intent.ACTION_VIEW);
						// note : apk package name : com.trendmicro.tmmspersonal.isp.full
						installApk.setDataAndType(Uri.parse(apkUri), "application/vnd.android.package-archive");
						startActivity(installApk);
					}
                }
            }
        }
    };

	private void downloadApp(Context context, String url) {
		
		// create folder for store download file
		File destinationDir = new File (Environment.getExternalStorageDirectory(), context.getPackageName());
		if (!destinationDir.exists()) {
		    destinationDir.mkdir(); // Don't forget to make the directory if it's not there
		} else {
			// remove all file in folder
			String[] children = destinationDir.list();
			for (int i = 0; i < children.length; i++) {
				new File(destinationDir, children[i]).delete();
			}
		}
		
		Uri source = Uri.parse(url);
		// Make a new request pointing to the mp3 url
		DownloadManager.Request request = new DownloadManager.Request(source);
		// Use the same file name for the destination
		File destinationFile = new File(destinationDir, source.getLastPathSegment());
		request.setDestinationUri(Uri.fromFile(destinationFile));
		// Add it to the manager
		final long downloadId = manager.enqueue(request);
		
		final ProgressDialog progressDialogDl = new ProgressDialog(context);
//			mProgressDialog.setTitle("Download");
		progressDialogDl.setMax(100);
		progressDialogDl.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialogDl.setTitle("Đang tải Sopcast...");

//			mProgressDialog.setProgressDrawable(getResources().getDrawable(R.drawable.progress));
		progressDialogDl.show();
		
		/*
		 * Show progress dialog downloading
		 */
		new Thread(new Runnable() {
		    @Override
		    public void run() {

		        boolean downloading = true;

		        while (downloading) {
		            DownloadManager.Query q = new DownloadManager.Query();
		            q.setFilterById(downloadId);

		            Cursor cursor = manager.query(q);
		            cursor.moveToFirst();
		            int bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
		            int bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
		            
		            if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
		                downloading = false;
		                // close dialog
		            	progressDialogDl.dismiss();
		            }

		            final int dlProgress = (bytesDownloaded * 100 / bytesTotal);
		            mParentAct.runOnUiThread(new Runnable() {
		                @Override
		                public void run() {
		                	progressDialogDl.setProgress((int) dlProgress);
		                }
		            });

		            cursor.close();
		        }
		    }
		}).start();
	}
}